<?php
require_once 'Base.php';

class PayBase extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->db = new Db();
    }

    //管理过大的日志文件
    public function logFileManger()
    {
        $fn = PAYLOG;
        if (filesize($fn) > 50000000) {
            file_put_contents($fn, '' . PHP_EOL);
        }
    }

    //读取微信发给服务器的流数据
    public function readStream()
    {
        $d = file_get_contents('php://input');
        if (empty($d)) {
            $d = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
        }
        return $d;
    }

    //写日志
    public function log($msg)
    {
        file_put_contents(PAYLOG, PHP_EOL . $msg . PHP_EOL, FILE_APPEND);
    }

    //记录数组
    public function logArray($arr)
    {
        if (is_array($arr)) {
            $msg = $this->arrayToString($arr);
            $this->log($msg);
        } else {
            $this->log($arr);
        }
    }

    //获取单品购物时的购物信息
    protected function getdanpinbody($spname, $jiage, $shuliang)
    {
        return "| {$spname} 单价 {$jiage} 数量  {$shuliang}";
    }

    //拆分商品数据
    public function getbody($sps, $dengji)
    {
        $body = '';

        while ($i = strpos($sps, ',')) {
            $tmp = substr($sps, 0, $i);
            //echo ' 本次结果=',$tmp;

            $j = strpos($tmp, ':');

            //echo ' 分隔符位置 '. $j;

            $tmp2 = substr($tmp, 0, $j);
            $tmp3 = substr($tmp, $j + 1);

            //echo ' id= ',$tmp2;
            //echo ' 数量= ',$tmp3;
            if (is_numeric($tmp2)) {
                $query = '';
                //等级不同价格不同

                if ($dengji == '0') {
                    $query = "select name,jiage from wmdc_shangpin where id={$tmp2}";
                } else if ($dengji == '1') {
                    $query = "select name,hyj as jiage from wmdc_shangpin where id={$tmp2}";

                } else if ($dengji == '2') {
                    $query = "select name,gjhyj as jiage from wmdc_shangpin where id={$tmp2}";
                }
                $result = mysqli_query($this->dbc, $query) or die(mysqli_error($this->dbc) . ' ' . $query);
                if (mysqli_num_rows($result) >= 1) {
                    while ($row = mysqli_fetch_array($result)) {
                        $body .= ' | ' . $row['name'] . ' 单价 ' . $row['jiage'] . ' 数量 ' . $tmp3;
                    }
                }
            }

            $sps = substr($sps, $i + 1);
            //echo ' 剩余结果= ',$sps;
        }

        //echo $body;
        //exit();
        return $body;
    }

    //把xml数据变成数组
    public function xmlToArray($xml)
    {
        if (!$xml) {
            return false;
        }
        //将XML转为array 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }

}
